package com.test.chinamobileai.service.lmpl;

import cn.hutool.core.date.DateUtil;
import com.test.chinamobileai.service.ChatService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.ai.chat.client.ChatClient;
import org.springframework.ai.chat.client.advisor.AbstractChatMemoryAdvisor;
import org.springframework.ai.chat.client.advisor.MessageChatMemoryAdvisor;
import org.springframework.ai.chat.client.advisor.QuestionAnswerAdvisor;
import org.springframework.ai.vectorstore.SearchRequest;
import org.springframework.ai.vectorstore.VectorStore;
import org.springframework.stereotype.Service;
import reactor.core.publisher.Flux;

@Slf4j
@Service
@RequiredArgsConstructor
public class ChatServicelmpl implements ChatService {

    private final ChatClient chatClient;
    private final VectorStore vectorStore;

    /**
     * 处理用户问题并返回流式响应内容
     *
     * @param question 用户输入的问题内容
     * @return 包含逐条响应内容和结束标记的响应流，每个元素为字符串格式
     */
    @Override
    public Flux<String> chatStream(String question, String sessionId) {
        SearchRequest request = SearchRequest.builder()
                .query(question)
                .topK(1)
                .build();
        return chatClient.prompt().advisors(advisor ->advisor.advisors(new QuestionAnswerAdvisor(vectorStore, request))
                .param(MessageChatMemoryAdvisor.CHAT_MEMORY_CONVERSATION_ID_KEY,sessionId))
                .user(question)
                .stream()
                .content()
                .concatWith(Flux.just("[DONE]"));
    }

}
